#include "smarthome.h"
#include "ui_smarthome.h"
#include "land.h"
#include <QtGui>
#include <QDialog>
#include <QtNetwork/QTcpSocket>
#include <QMessageBox>

Smarthome::Smarthome(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Smarthome)
{
    ui->setupUi(this);
    weightdialog = new Widget();
    this->setMinimumSize(800,480);
    this->setMaximumSize(800,480);
    ui->label->setMinimumSize(480,320);
    ui->label->setMaximumSize(480,320);
    pixmap=new QPixmap();
    this->socket=NULL;
    ui->pushButton->setEnabled(true);//开启视频按钮的初值给true
    ui->pushButton_2->setEnabled(false);//关闭视频按钮的初值给false

}

Smarthome::~Smarthome()
{
    delete ui;
}

void Smarthome::on_pushButton_clicked()
{
     connect(this->socketCom,SIGNAL(readyRead()),this,SLOT(comread()));

     this->socket = new QTcpSocket();
     this->socket->connectToHost("192.168.1.207",8888);
     ui->pushButton->setEnabled(false);//开启视频后让此按钮变灰
     ui->pushButton_2->setEnabled(true);//已经开启视频后让关闭视频按钮变黑（true）

     connect(this->socket,SIGNAL(connected()),this,SLOT(msconnected()));
     connect(this->socket,SIGNAL(disconnected()),this,SLOT(msdisconnected()));

     this->mypicsocket = new QTcpSocket;
     mypicsocket->connectToHost("192.168.1.207",8888);
     connect(this->mypicsocket,SIGNAL(connected()),this,SLOT(rev_pic()));
     connect(this->mypicsocket,SIGNAL(disconnected()),this,SLOT(pic_misconnected()));
}

void Smarthome::comread()
{
    char  buf[50] = {0};
    memset(buf,0,50);
    this->socketCom->read(buf,50);
     str =QString::fromLocal8Bit(buf);
   // ui->textBrowser->insertPlainText(str);
    ui->textBrowser->append(str);
    QStringList sl = str.split("-");
    ui->lineEdit_2->setText(sl.at(2));
    if(0 == QString::compare(sl.at(0),"XS"))
    {
        qDebug() << "charts";
        this->weightdialog->setStrData(QLatin1String(buf));
        weightdialog->comread();
    }
}
void Smarthome::msconnected()
{
    qDebug() << "connected";
    timer = new QTimer(this);
    timer->start(100);
    connect(timer,SIGNAL(timeout()),this,SLOT(updatepic()));
    timer->start(100);
}
void Smarthome::msdisconnected()
{
    if(timer->isActive())
        timer->stop();
    ui->pushButton->setEnabled(true);//按下关闭视频按钮后让开启视频按钮变黑（true）
    ui->pushButton_2->setEnabled(false);//按下关闭视频按钮后让关闭按钮变灰（false）
    this->socket->close();
    this->socket = NULL;
}
void Smarthome::updatepic()
{
    int ret;
    char *request = "pic";      //请求命令
    char response[20];          //服务器发给QT的回复
    char *len;                  //
    unsigned int piclen;        //图片长度
    char picbuf[1024 * 1024];   //存放图片



    ret = this->socket->write(request, strlen(request));  //发送请求图片命令

   // QString str =QString::fromLocal8Bit(request);
   // ui->textBrowser->append(str);

    if (ret != strlen(request)) {
        qDebug() << "send request failed";
        timer->stop();
        this->socket->close();
    }

    this->socket->flush();    //刷新socket
    this->socket->waitForReadyRead(30000);

    memset(response, 0, sizeof(response));
    ret = this->socket->read(response, sizeof(response));
    if (ret != sizeof(response)) {
        qDebug() << "recv response failed";
        timer->stop();
        this->socket->close();
        this->socket = NULL;
    }

    len = strstr(response, "len");
    if (len == NULL) {
        qDebug() << "response header is error";
        timer->stop();
        this->socket->close();
        this->socket = NULL;
    }

    *len = '\0';
    //从response中读取图片长度
    piclen = atoi(response);

    //qDebug() << "piclen: " << piclen;

    int total = 0;
    //循环读取pic信息
    while (total < piclen) {
        ret = this->socket->read(picbuf+total, piclen-total);
        if (ret < 0) {
            qDebug() << "recv pic failed" << ret;
            timer->stop();
            this->socket->close();
            this->socket = NULL;
            return;
        } else if (ret == 0) {
            this->socket->waitForReadyRead(30000);
            continue;
        } else
            total += ret;

        //qDebug() << "total: " << total;
    }

    pixmap->loadFromData((const uchar *)picbuf, piclen, "JPEG");
    ui->label->setPixmap(*pixmap);
}

void Smarthome::on_pushButton_2_clicked()
{
    qDebug() << "total:----11--------------- ";
    if(timer->isActive())
        timer->stop();
   qDebug() << "total:------------------- ";
    ui->pushButton->setEnabled(true);//按下关闭视频按钮后让开启视频按钮变黑（true）
    ui->pushButton_2->setEnabled(false);//按下关闭视频按钮后让关闭按钮变灰（false）
}

void Smarthome::on_pushButton_3_clicked()
{
    char buf[20]="DOOR_ON";
    this->socketCom->write(buf,7);
    QString str =QString::fromLocal8Bit(buf);
 //   ui->textBrowser->insertPlainText(str);
    ui->textBrowser->append(str);
}

void Smarthome::on_pushButton_4_clicked()
{
    if(ui->pushButton_4->text()=="开警报")
    {
        char buf[20]="OPEN_WARNING";
        this->socketCom->write(buf,12);
        QString str =QString::fromLocal8Bit(buf);
        ui->textBrowser->append(str);

        ui->pushButton_4->setText("关警报");
    }
    else if(ui->pushButton_4->text()=="关警报")
    {
        char buf[20]="CLOSE_WARNING";
        this->socketCom->write(buf,12);
        QString str =QString::fromLocal8Bit(buf);
        ui->textBrowser->append(str);

        ui->pushButton_4->setText("开警报");
    }
}

void Smarthome::on_pushButton_5_clicked()
{
    if(ui->pushButton_5->text()=="开风扇")
    {
        char buf[20]="OPEN_FAN";
        this->socketCom->write(buf,8);
        QString str =QString::fromLocal8Bit(buf);
        ui->textBrowser->append(str);

        ui->pushButton_5->setText("关风扇");
    }
    else if(ui->pushButton_5->text()=="关风扇")
    {
        char buf[20]="CLOSE_FAN";
        this->socketCom->write(buf,9);
        QString str =QString::fromLocal8Bit(buf);
        ui->textBrowser->append(str);
        ui->pushButton_5->setText("开风扇");
    }
}

void Smarthome::on_pushButton_6_clicked()
{
    QByteArray commond = 0;
    commond.append("CX-");
    commond.append(ui->lineEdit->text());
    commond.append("-");
    commond.append(ui->lineEdit_2->text());
    this->socketCom->write(commond,strlen(commond));
    qDebug() << commond;
}

void Smarthome::on_pushButton_7_clicked()
{
    QByteArray commond = 0;
    commond.append("TJ-");
    commond.append(ui->lineEdit->text());
    commond.append("-");
    commond.append(ui->lineEdit_2->text());
    this->socketCom->write(commond,strlen(commond));
    qDebug() << commond;
}

void Smarthome::on_pushButton_8_clicked()
{
    QByteArray commond = 0;
    commond.append("XG-");
    commond.append(ui->lineEdit_3->text());
    commond.append("-");
    commond.append(ui->lineEdit_4->text());
    this->socketCom->write(commond,strlen(commond));
    qDebug() << commond;

    if(this->str.trimmed()==tr("XG-OK"))
    {
        QMessageBox::information(this,tr("information"),tr("修改成功"),QMessageBox::Yes);
    }
    else if(this->str.trimmed()==tr("XG-ER"))
    {
        QMessageBox::warning(this,tr("warning"),tr("修改失败，请重新修改"),QMessageBox::Yes);//如果不正确，弹出警告信息
    }
}



void Smarthome::on_pushButton_9_clicked()
{
    QByteArray commond = 0;
    commond.append("ZJ-");
    commond.append(ui->lineEdit_5->text());
    commond.append("-");
    commond.append(ui->lineEdit_6->text());
    this->socketCom->write(commond,strlen(commond));
    qDebug() << commond;

    if(this->str.trimmed()==tr("ZJ-OK"))
    {
        QMessageBox::information(this,tr("information"),tr("添加成功"),QMessageBox::Yes);
    }
    else if(this->str.trimmed()==tr("ZJ-ER"))
    {
        QMessageBox::warning(this,tr("warning"),tr("该卡号已存在，请重新输出"),QMessageBox::Yes);//如果不正确，弹出警告信息
    }
}

void Smarthome::on_pushButton_10_clicked()
{
    this->mypicsocket->write("screen of picture",50);
    picture.picsocket = this->mypicsocket;
    this->picture.show();
    picture.receive_picture();
}
void Smarthome::rev_pic()
{
    qDebug() << "pic connect ok";

}

void Smarthome::pic_misconnected()
{
    mypicsocket->close();
}

void Smarthome::on_pushButton_11_clicked()
{
    QByteArray commond = 0;
    commond.append("SX-");
    commond.append(ui->lineEdit_5->text());
    commond.append("-");
    commond.append(ui->lineEdit_6->text());

    qDebug() << commond;

    int num = strlen(ui->lineEdit_6->text().toLocal8Bit());

    if(num != 10)
    {
        QMessageBox::warning(this,tr("warning"),tr("卡号位数不对，请重新输入"),QMessageBox::Yes);
    }
    else
    {
        this->socketCom->write(commond,strlen(commond));
    }
}

void Smarthome::on_pushButton_12_clicked()
{
    this->weightdialog->setSocket(this->socketCom);
    weightdialog->show();
}
